package rpc_netty.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LoggingHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rpc_1.Impl.HelloServiceImpl;
import rpc_netty.server.ServiceProvider.DefaultServiceProvider;
import rpc_1.Service.RpcException;
import rpc_1.interfaces.HelloService;
import rpc_netty.Encoder.CommonDecoder;
import rpc_netty.Encoder.CommonEncoder;
import rpc_netty.Handler.NettyServerHandler;
import rpc_netty.Serializer.KryoSerializer;
import rpc_netty.interfaces.RpcServer;

public class NettyServer implements RpcServer{
    private static final Logger logger= LoggerFactory.getLogger(NettyServer.class);

    @Override
    public void start(int port) {
        NioEventLoopGroup boss = new NioEventLoopGroup();
        NioEventLoopGroup worker=new NioEventLoopGroup();
        try{
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(boss,worker)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler())
                    .option(ChannelOption.SO_BACKLOG,256)//指定tcp全连接队列大小
                    .option(ChannelOption.SO_KEEPALIVE,true)//心跳机制
                    .childOption(ChannelOption.TCP_NODELAY,true)//关闭nagle算法，保证有数据就及时发送
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            //pipeline.addLast(new CommonEncoder(new JsonSerializer()));
                            pipeline.addLast(new CommonEncoder(0));
                            pipeline.addLast(new CommonDecoder());
                            pipeline.addLast(new NettyServerHandler());
                        }
                    });
            ChannelFuture future=serverBootstrap.bind(port).sync();
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
            logger.error("error when starting the server");
        }finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }

    @Override
    public <T> void publishService(T service, String serviceName) {

    }

    public static void main(String[] args) throws RpcException {
        HelloService helloService=new HelloServiceImpl();
        DefaultServiceProvider defaultserviceProvider=new DefaultServiceProvider();
        defaultserviceProvider.provide(helloService);
        NettyServer nettyServer = new NettyServer();
        nettyServer.start(8825);
    }

}
